﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Xfs
{
    [XfsMessageHandler(XfsSenceType.XfsClient)]
    public class C4S_UnitHandler : XfsAMRpcHandler<C4S_Unit, S4C_Unit>
    {
        protected override void Run(XfsSession session, C4S_Unit message, Action<S4C_Unit> reply)
        {
            if (message.Roleid != 0)
            {
                if (XfsGame.XfsSence.GetComponent<XfsUnitComponent>().Units.TryGetValue(message.Roleid, out XfsUnit? unit0))
                {
                    S4C_Unit response = new S4C_Unit() { Roleid = message.Roleid, Roleinstanceid = unit0.InstanceId };
                    reply(response);                   

                    Console.WriteLine(XfsTimeHelper.CurrentTime() + " " + this.GetType().Name + " 30. id/inid/units: " + message.Roleid + "/" + message.Roleinstanceid + "/" + XfsGame.XfsSence.GetComponent<XfsUnitComponent>().Units.Count);
                }
                else
                {
                    XfsUnit? unit = XfsComponentFactory.CreateWithId<XfsUnit>(message.Roleid);
                    if (unit == null) return;

                    unit.AddComponent<XfsMoveComponent>();
                    unit.AddComponent<XfsMailboxComponent>();

                    XfsGame.XfsSence.GetComponent<XfsUnitComponent>().Units.Add(unit.Id, unit);
                    XfsGame.XfsSence.GetComponent<XfsUnitComponent>().Ids.Add(unit.Id, unit.InstanceId);

                    S4C_Unit response = new S4C_Unit() { Roleid = message.Roleid, Roleinstanceid = unit.InstanceId };
                    reply(response);

                    Console.WriteLine(XfsTimeHelper.CurrentTime() + " " + this.GetType().Name + " 40. id/inid/units: " + message.Roleid + "/" + message.Roleinstanceid + "/" + XfsGame.XfsSence.GetComponent<XfsUnitComponent>().Units.Count);
                }
            }
        }


    }
}
